﻿namespace WebPacker.Logger
{
	using System;
	using NLogLevel = NLog.LogLevel;

	public class NLogLogger : ILogger
	{
		private readonly object syncRoot = new object();
		private string name;
		private NLog.Logger logger;
		private bool resetLogger = true;

		public bool Enabled { get; set; }

		public string Name
		{
			get
			{
				return name;
			}

			set
			{
				name = value;
				resetLogger = true;
			}
		}

		public void Log(LogLevel logLevel, LogMessageBuilder messageBuilder)
		{
			if (Enabled)
			{
				PrepareLogger();
				logger.Log(GetNLogLevel(logLevel), messageBuilder());
			}
		}

		public void LogException(LogLevel logLevel, LogMessageBuilder messageBuilder, Exception exception)
		{
			if (Enabled)
			{
				PrepareLogger();

				var nlogLevel = GetNLogLevel(logLevel);

				if (logger.IsEnabled(nlogLevel))
				{
					logger.LogException(nlogLevel, messageBuilder(), exception);
				}
			}
		}

		private static NLogLevel GetNLogLevel(LogLevel logLevel)
		{
			switch (logLevel)
			{
				case LogLevel.Debug:
					return NLogLevel.Debug;

				case LogLevel.Information:
					return NLogLevel.Info;

				case LogLevel.Warning:
					return NLogLevel.Warn;

				default:
					return NLogLevel.Error;
			}
		}

		private void PrepareLogger()
		{
			if (resetLogger)
			{
				lock (syncRoot)
				{
					if (resetLogger)
					{
						logger = NLog.LogManager.GetLogger(name);
						resetLogger = false;
					}
				}
			}
		}
	}
}
